<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Snake Game</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f0f0f0;
            margin: 0;
            padding: 20px;
        }
        
        #game-container {
            display: inline-block;
            position: relative;
            margin: 20px auto;
        }
        
        #game-canvas {
            background-color: #fff;
            border: 2px solid #333;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        }
        
        #score-board {
            margin: 20px auto;
            padding: 10px;
            background-color: #333;
            color: white;
            border-radius: 5px;
            width: 300px;
        }
        
        #controls {
            margin: 20px auto;
            padding: 15px;
            background-color: #eee;
            border-radius: 5px;
            width: 300px;
        }
        
        button {
            padding: 8px 15px;
            margin: 5px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        .snake-head {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>WebSocket Snake Game</h1>
    
    <div id="game-container">
        <canvas id="game-canvas" width="600" height="300"></canvas>
    </div>
    
    <div id="score-board">
        <h2>Score: <span id="score">0</span></h2>
        <p>Status: <span id="status">Waiting to join...</span></p>
    </div>
    
    <div id="controls">
        <h3>Controls</h3>
        <p>Use arrow keys or buttons below to control your snake</p>
        <button id="up-btn">↑ Up</button><br>
        <button id="left-btn">← Left</button>
        <button id="right-btn">→ Right</button><br>
        <button id="down-btn">↓ Down</button>
    </div>
    
    <script>
        const canvas = document.getElementById('game-canvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const statusElement = document.getElementById('status');
        
        // WebSocket connection
        const ws = new WebSocket('ws://120.46.0.237:7070');
        
        // Game state
        let gameState = {
            width: 0,
            height: 0,
            snakes: [],
            foods: [],
            playerId: null
        };
        
        // Colors for snakes
        const snakeColors = {
            1: '#3498db', // Blue
            2: '#2ecc71', // Green
            3: '#e74c3c', // Red
            4: '#f39c12'  // Orange
        };
        
        // Connect to WebSocket server
        ws.onopen = function() {
            statusElement.textContent = 'Connected to server. Joining game...';
            
            // Send join request
            ws.send(JSON.stringify({
                type: 'join'
            }));
        };
        
        ws.onmessage = function(event) {
            const data = JSON.parse(event.data);
            
            if (data.type === 'player_id') {
                gameState.playerId = data.id;
                statusElement.textContent = 'Playing (Player ' + gameState.playerId + ')';
            } else {
                // Update game state
                gameState.width = data.width;
                gameState.height = data.height;
                gameState.snakes = data.snakes;
                gameState.foods = data.foods;
                
                // Find player snake
                const playerSnake = gameState.snakes.find(snake => snake.id === gameState.playerId);
                if (playerSnake) {
                    scoreElement.textContent = playerSnake.score;
                    
                    if (playerSnake.status === 1) {
                        statusElement.textContent = 'Game Over: Hit the wall!';
                    } else if (playerSnake.status === 2) {
                        statusElement.textContent = 'Game Over: Hit yourself!';
                    }
                }
                
                // Render game
                renderGame();
            }
        };
        
        ws.onclose = function() {
            statusElement.textContent = 'Disconnected from server';
        };
        
        ws.onerror = function(error) {
            statusElement.textContent = 'Error: ' + error.message;
        };
        
        // Handle keyboard controls
        document.addEventListener('keydown', function(event) {
            if (!gameState.playerId) return;
            
            let direction;
            
            switch(event.key) {
                case 'ArrowUp':
                case 'w':
                case 'W':
                    direction = 'up';
                    break;
                case 'ArrowDown':
                case 's':
                case 'S':
                    direction = 'down';
                    break;
                case 'ArrowLeft':
                case 'a':
                case 'A':
                    direction = 'left';
                    break;
                case 'ArrowRight':
                case 'd':
                case 'D':
                    direction = 'right';
                    break;
                default:
                    return;
            }
            
            ws.send(JSON.stringify({
                type: 'direction',
                direction: direction
            }));
        });
        
        // Button controls
        document.getElementById('up-btn').addEventListener('click', function() {
            sendDirection('up');
        });
        
        document.getElementById('down-btn').addEventListener('click', function() {
            sendDirection('down');
        });
        
        document.getElementById('left-btn').addEventListener('click', function() {
            sendDirection('left');
        });
        
        document.getElementById('right-btn').addEventListener('click', function() {
            sendDirection('right');
        });
        
        function sendDirection(direction) {
            if (!gameState.playerId) return;
            
            ws.send(JSON.stringify({
                type: 'direction',
                direction: direction
            }));
        }
        
        // Render game
        function renderGame() {
            // Clear canvas
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // Calculate scale factors
            const cellSize = Math.min(
                canvas.width / gameState.width,
                canvas.height / gameState.height
            );
            
            const offsetX = (canvas.width - gameState.width * cellSize) / 2;
            const offsetY = (canvas.height - gameState.height * cellSize) / 2;
            
            // Draw walls
            ctx.fillStyle = '#333';
            ctx.fillRect(offsetX, offsetY, gameState.width * cellSize, cellSize);
            ctx.fillRect(offsetX, offsetY + (gameState.height - 1) * cellSize, 
                         gameState.width * cellSize, cellSize);
            ctx.fillRect(offsetX, offsetY, cellSize, gameState.height * cellSize);
            ctx.fillRect(offsetX + (gameState.width - 1) * cellSize, offsetY, 
                         cellSize, gameState.height * cellSize);
            
            // Draw food
            ctx.fillStyle = '#e74c3c';
            gameState.foods.forEach(food => {
                ctx.beginPath();
                ctx.arc(
                    offsetX + food.x * cellSize + cellSize/2,
                    offsetY + food.y * cellSize + cellSize/2,
                    cellSize/2 - 1,
                    0,
                    Math.PI * 2
                );
                ctx.fill();
            });
            
            // Draw snakes
            gameState.snakes.forEach(snake => {
                const isPlayer = snake.id === gameState.playerId;
                const color = snakeColors[snake.color] || '#95a5a6';
                
                ctx.fillStyle = color;
                
                snake.body.forEach((segment, index) => {
                    const x = offsetX + segment.x * cellSize;
                    const y = offsetY + segment.y * cellSize;
                    
                    if (index === 0) {
                        // Draw head differently
                        ctx.fillRect(x, y, cellSize, cellSize);
                        
                        // Draw eyes for player's snake
                        if (isPlayer) {
                            const eyeSize = cellSize / 5;
                            const eyeOffset = cellSize / 4;
                            
                            ctx.fillStyle = 'white';
                            ctx.fillRect(x + eyeOffset, y + eyeOffset, eyeSize, eyeSize);
                            ctx.fillRect(x + cellSize - eyeOffset - eyeSize, y + eyeOffset, eyeSize, eyeSize);
                            ctx.fillStyle = 'black';
                            ctx.fillRect(x + eyeOffset + 1, y + eyeOffset + 1, eyeSize - 2, eyeSize - 2);
                            ctx.fillRect(x + cellSize - eyeOffset - eyeSize + 1, y + eyeOffset + 1, eyeSize - 2, eyeSize - 2);
                            
                            ctx.fillStyle = color;
                        }
                    } else {
                        // Draw body segment
                        ctx.beginPath();
                        ctx.arc(
                            x + cellSize/2,
                            y + cellSize/2,
                            cellSize/2 - 1,
                            0,
                            Math.PI * 2
                        );
                        ctx.fill();
                    }
                });
            });
        }
        
        // Handle window resize
        window.addEventListener('resize', function() {
            // Adjust canvas size while maintaining aspect ratio
            const container = document.getElementById('game-container');
            const aspectRatio = gameState.width / gameState.height;
            
            if (window.innerWidth < 800) {
                const newWidth = Math.min(window.innerWidth - 40, 600);
                canvas.width = newWidth;
                canvas.height = newWidth / aspectRatio;
            } else {
                canvas.width = 600;
                canvas.height = 300;
            }
            
            renderGame();
        });
    </script>
</body>
</html>